package com.yuyou.fn.controller;

import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.activity.entity.Activity;
import com.yuyou.fn.activity.entity.ActivityCampusSession;

import com.yuyou.fn.activity.service.*;
import com.yuyou.fn.activity.vo.*;

import com.yuyou.fn.common.util.BeanUtils;

import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;

import com.yuyou.fn.platform.permission.DataPermission;

import com.yuyou.fn.util.Excels;
import com.yuyou.fn.util.Webs;
import io.swagger.annotations.ApiOperation;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * Created by itachi on 2017/04/05.
 */
@Controller
@RequestMapping("/api/admin/activity")
public class AdminActivityController extends ApiBaseController {

    @Resource
    private IActivityService activityService;

    @Resource
    private IActivityCampusService activityCampusService;

    @Resource
    private IActivityRegSituationService activityRegSituationService;

    @Resource
    private IActivityTargetService activityTargetService;

    @Resource
    private IActivityInventorySettingService activityInventorySettingService;

    @Resource
    private IActivityCampusInventoryService activityCampusInventoryService;

    @Resource
    private ICampusService campusService;

    @Resource
    private IBaseGradeService baseGradeService;


    @ApiOperation("活动列表")
    @RequestMapping(value = "/findActivityDetailPage" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ActivityDetailVo>> findActivityDetailPage(@Valid @ModelAttribute ActivityQueryVo activityQueryVo,@RequestParam("pageNo")int pageNo,@RequestParam("pageSize")int pageSize, HttpServletRequest request){
        Page<ActivityDetailVo> activityDetailPage = activityService.findActivityDetailPage(activityQueryVo, pageNo, pageSize);
        return ReturnResult.success(activityDetailPage);
    }

    @ApiOperation("下载活动导入模板")
    @RequestMapping(value = "/downloadActivityTemplate" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void downloadActivityTemplate(@RequestParam(value = "activityId")long activityId , HttpServletRequest request, HttpServletResponse response ) throws IOException {
        Activity activity=activityService.findById(activityId);
        List<ActivityCampusDetailVo> activityCampusDetailVoList=activityCampusService.findActivityCampusListByActivityId(activityId);
        List<Campus> campusList=campusService.findByIds(BeanUtils.toList(activityCampusDetailVoList,"campusId"));
        List<BaseGrade> baseGradeList=baseGradeService.findAllOrderGrade();
        Webs.writeExcel(request,response,this.activity2ExcelForInput(activity,campusList,baseGradeList,activityCampusDetailVoList),activity.getActivityName()+"导入模板");
        return ;
    }
    @ApiOperation("导入活动报名数据")
    @RequestMapping(value = "/importActivityRegSituation", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> importActivityRegSituation(@RequestParam("activityId")long activityId, MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ImportParams params = new ImportParams();
        List<ImportActivityRegVo> importCourseClassVoList = ExcelImportUtil.importExcel(inputStream, ImportActivityRegVo.class, params);
        for (ImportActivityRegVo importActivityRegVo:importCourseClassVoList){
            importActivityRegVo.setSessionNo(Integer.parseInt(importActivityRegVo.getSessionName().replace("第","").replace("场","")));
        }
        activityRegSituationService.importActivityRegSituation(activityId,importCourseClassVoList);
        return ReturnResult.success("ok");
    }



    public XSSFWorkbook activity2ExcelForInput(Activity activity, List<Campus> campusList,List<BaseGrade> baseGradeList, List<ActivityCampusDetailVo> activityCampusDetailVoList) {
        String sheetName = activity.getActivityName()+"导入";
        XSSFWorkbook excel = new XSSFWorkbook();
        XSSFSheet sheet = excel.createSheet(sheetName);
        XSSFRow firstRow = sheet.createRow(0);

        String[] titles = new String[]{"意向校区","场次", "学生姓名", "学生电话", "年级"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }

        List<String> campusNames = BeanUtils.toList(campusList, "campusName");
        Map<Long,Campus> campusMap=BeanUtils.toMap(campusList,"campusId");
        Excels.createDict(excel,"意向校区",campusNames);

        List<String> gradeNames=BeanUtils.toList(baseGradeList,"gradeName");
        Excels.createDict(excel,"年级",gradeNames);

        for(ActivityCampusDetailVo activityCampusDetailVo : activityCampusDetailVoList ){
            List<ActivityCampusSession> subs = activityCampusDetailVo.getActivityCampusSessionList();
            if(subs == null  ){
                subs = Collections.EMPTY_LIST ;
            }
            List<String> sessionNos=new ArrayList<>(subs.size());
            for (ActivityCampusSession activityCampusSession:subs){
                sessionNos.add("第"+activityCampusSession.getSessionNo().toString()+"场");
            }
            Campus campus=campusMap.get(activityCampusDetailVo.getCampusId());
            Excels.createDict(excel,campus.getCampusName() ,sessionNos);
        }

        Excels.addFormulaListConstraint(sheet, "意向校区", 1 , 1024 * 5  , 0, 0);
        Excels.addFormulaListConstraint(sheet, "年级", 1 , 1024 * 5  , 4, 4);
        for(int i = 1 ; i < 1024 * 5 ; i++ ){
            Excels.addFormulaListConstraint(sheet, String.format("INDIRECT(A%d)" , (i  + 1 )), i , i  , 1, 1 );
        }

        return excel;
    }




    @ApiOperation("单个活动详情")
    @RequestMapping(value = "/findOneActivityDetail" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<ActivityDetailVo> findOneActivityDetail(@RequestParam("activityId")long activityId, HttpServletRequest request){
        ActivityDetailVo activityQueryVo=activityService.findActivityDetailById(activityId);
        return ReturnResult.success(activityQueryVo);
    }


    @ApiOperation("新建或者更新活动")
    @RequestMapping(value = "/saveOrUpdateActivity" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateActivity(@Valid @RequestBody ActivitySaveUpdateVo activitySaveUpdateVo,  HttpServletRequest request){
        activityService.saveOrUpdateActivityVo(activitySaveUpdateVo);
        return ReturnResult.success("ok");
    }

    @ApiOperation("获取活动关联的校区")
    @RequestMapping(value = "/findActivityCampusListByActivityId" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ActivityCampusDetailVo>> findActivityCampusListByActivityId( @RequestParam("activityId")long activityId, HttpServletRequest request){
        List<ActivityCampusDetailVo> activityCampusDetailVos = activityCampusService.findActivityCampusListByActivityId(activityId);
        return ReturnResult.success(activityCampusDetailVos);
    }

    @ApiOperation("设置活动关联校区")
    @RequestMapping(value = "/saveActivityCampus" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveActivityCampus(@Valid @RequestBody ActivityCampusSaveVo activityCampusSaveVo,HttpServletRequest request){
        activityCampusService.saveActivityCampus(activityCampusSaveVo);
        return ReturnResult.success("ok");
    }

    @ApiOperation("查看活动报名签到信息")
    @RequestMapping(value = "/findActivityRegSituationPage" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ActivityRegSituationDetailVo>> findActivityRegSituationPage(@Valid @ModelAttribute ActivityRegSituationQueryVo activityRegSituationQueryVo, @RequestParam("pageNo")int pageNo,@RequestParam("pageSize")int pageSize,HttpServletRequest request){
        DataPermission dataPermission=this.getDataPermission(request);
        Page<ActivityRegSituationDetailVo> activityRegSituationPage = activityRegSituationService.findActivityRegSituationPage(dataPermission,activityRegSituationQueryVo, pageNo, pageSize);
        return ReturnResult.success(activityRegSituationPage);
    }

    @ApiOperation("导出活动报名签到信息")
    @RequestMapping(value = "/exportActivityRegSituation", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportCustomerResource(@Valid @ModelAttribute ActivityRegSituationQueryVo activityRegSituationQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        DataPermission dataPermission=this.getDataPermission(request);
        Webs.writeExcel(request, response, activityRegSituationService.exportActivityRegSituationDetail(dataPermission,activityRegSituationQueryVo), "活动报名签到信息");
        return ReturnResult.success("ok");
    }





    @ApiOperation("活动目标列表")
    @RequestMapping(value = "/findActivityTargetPage" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ActivityTargetDetailVo>> findActivityTargetPage(@Valid @ModelAttribute ActivityTargetQueryVo activityTargetQueryVo, @RequestParam("pageNo")int pageNo, @RequestParam("pageSize")int pageSize, HttpServletRequest request){
        DataPermission dataPermission=this.getDataPermission(request);
        Page<ActivityTargetDetailVo> activityDetailPage = activityTargetService.findActivityTargetPageByQueryVo(dataPermission, activityTargetQueryVo, pageNo, pageSize);
        return ReturnResult.success(activityDetailPage);
    }

    @ApiOperation("导出活动目标列表")
    @RequestMapping(value = "/exportActivityTarget", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportActivityTarget(@Valid @ModelAttribute ActivityTargetQueryVo activityTargetQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        DataPermission dataPermission=this.getDataPermission(request);
        Webs.writeExcel(request, response, activityTargetService.exportActivityTarget(dataPermission,activityTargetQueryVo), "活动目标列表");
        return ReturnResult.success("ok");
    }


    @ApiOperation("活动目标编辑")
    @RequestMapping(value = "/changeActivityTargetById" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> changeActivityTargetById(@Valid @ModelAttribute ActivityTargetChangeVo activityTargetChangeVo, HttpServletRequest request){
        activityTargetService.changeActivityTargetByVo(activityTargetChangeVo);
        return ReturnResult.success("ok");
    }


    @ApiOperation("库存设置列表")
    @RequestMapping(value = "/findActivityInventorySetting" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ActivityInventorySettingDetailVo>> findActivityInventorySetting(@Valid @ModelAttribute ActivityInventoryQueryVo activityInventoryQueryVo, @RequestParam("pageNo")int pageNo,@RequestParam("pageSize")int pageSize,HttpServletRequest request){
        Page<ActivityInventorySettingDetailVo> activityInventoryDetailPage = activityInventorySettingService.findActivityInventoryDetailPage(activityInventoryQueryVo, pageNo, pageSize);
        return ReturnResult.success(activityInventoryDetailPage);
    }

    @ApiOperation("保存更新库存设置")
    @RequestMapping(value = "/saveOrUpdateActivityInventorySetting" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateActivityInventorySetting(@Valid @RequestBody ActivityInventorySaveOrUpdateVo activityInventorySaveOrUpdateVo,HttpServletRequest request){
        activityInventorySettingService.saveOrUpdateActivityInventorySetting(activityInventorySaveOrUpdateVo);
        return ReturnResult.success("ok");
    }

    @ApiOperation("单个库存设置详情")
    @RequestMapping(value = "/activityInventorySettingDetail" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<ActivityInventorySettingDetailVo> activityInventorySettingDetail(@RequestParam("activityInventorySettingId") long activityInventorySettingId,HttpServletRequest request){
        ActivityInventorySettingDetailVo settingDetailVo = activityInventorySettingService.findActivityInventoryDetailById(activityInventorySettingId);
        return ReturnResult.success(settingDetailVo);
    }

    @ApiOperation("查询校区库存")
    @RequestMapping(value = "/activityCampusInventoryDetail" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ActivityCampusInventoryDetailVo> > activityInventorySettingDetail(@Valid @ModelAttribute ActivityCampusInventoryQueryVo activityCampusInventoryQueryVo, @RequestParam("pageNo")int pageNo,@RequestParam("pageSize")int pageSize,HttpServletRequest request){
        DataPermission dataPermission=this.getDataPermission(request);
        Page<ActivityCampusInventoryDetailVo> inventoryDetailVoPage = activityCampusInventoryService.findInventoryDetailBySettingId(dataPermission,  activityCampusInventoryQueryVo, pageNo, pageSize);
        return ReturnResult.success(inventoryDetailVoPage);
    }

    @ApiOperation("根据id更新校区库存")
    @RequestMapping(value = "/updateActivityCampusInventory" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> activityInventorySettingDetail(@Valid @ModelAttribute ActivityCampusInventoryUpdateVo activityCampusInventoryUpdateVo,HttpServletRequest request){
        activityCampusInventoryService.updateByIdAndUpdateVo(activityCampusInventoryUpdateVo.getActivityCampusInventoryId(),activityCampusInventoryUpdateVo);
        return ReturnResult.success("ok");
    }


    @ApiOperation("导出校区库存")
    @RequestMapping(value = "/exportActivityCampusInventory", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportActivityCampusInventory(@Valid @ModelAttribute  ActivityCampusInventoryQueryVo activityCampusInventoryQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        DataPermission dataPermission=this.getDataPermission(request);
        Webs.writeExcel(request, response, activityCampusInventoryService.exporteActivityCampusInventory(dataPermission,activityCampusInventoryQueryVo), "校区库存使用情况");
        return ReturnResult.success("ok");
    }


}
